package com.theydream.qeechain.map;

import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.theydream.qeechain.R;
import com.theydream.qeechain.ARcaught.ARClick;
import com.theydream.qeechain.globaldata.GlobalData;
import com.theydream.qeechain.globaldata.ItemListClass;
import com.theydream.qeechain.globaldata.definition.LocationData;
import com.theydream.qeechain.model.map.MyLocationManager;

/**
 * author Sum
 * Map Activity that show the map and all the overlays and location manager
 *
 */


public class Map extends MapActivity{
	// ================================================================
	// Constant
	// ================================================================
	private double RADIUS=1000.0;

	// ================================================================
	// Fields
	// ================================================================

	private MapView mapView;
	private MyLocationOverlay mLocationOverlay;
	private MapController mapController;
	private LocationManager mLocationManager;
	private List<Overlay> mapOverlays;
//	private SpotDbAdapter mDbHelper;
	private Projection projection;
	private GeoPoint topLeft;
	private GeoPoint bottomRight;
	private double topLat;
	private double topLon;
	private double bottomLat;
	private double bottomLon;
	private Context mContext;
	private AttractionLayer attLayer;
	private ProgressDialog dialog;
	private MyLocationManager myLocationManager;
	private AttractionLayer missionLayer; 
	private int mMapOption=1; 

	// ================================================================
	// Inheried methods
	// ================================================================

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchmap);
	
		Button btnAR=(Button) findViewById(R.id.btnToAR);
		btnAR.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				startActivity(new Intent(Map.this,ARClick.class));
			}
		});
		Button btnSwitchMap = (Button) findViewById(R.id.btnSwtichMap);
		btnSwitchMap.setVisibility(View.GONE);
		btnSwitchMap.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				switch (mMapOption)
				{
					case 1:
					{
						mapOverlays.remove(attLayer);
						mMapOption++;
						break;
					}
					case 2:
					{
						mapOverlays.remove(missionLayer);
						mapOverlays.add(attLayer);
						mMapOption++;
						break;
					}
					case 3:
					{	
						mapOverlays.add(missionLayer);
						mMapOption=1;
						break;
					}
					
				}
				mapView.invalidate();
				
			}
		});
		// Create Google Map View
		mContext=this;
		//Button btnLocateMe=(Button) findViewById(R.id.btnLocateMe);
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapController = mapView.getController();
		mapOverlays = mapView.getOverlays();
		initMyLocation();

		
		attLayer = new AttractionLayer(this.getResources().getDrawable(R.drawable.map_marker), this);
		missionLayer=new AttractionLayer(this.getResources().getDrawable(R.drawable.mission),this);
		//getScreenLocation(mapView);
		LoadItemFromDataBaseTask loadItem=new LoadItemFromDataBaseTask();
		loadItem.execute();

//		btnLocateMe.setOnClickListener(new OnClickListener(){
//
//			public void onClick(View arg0) 
//			{
//				
//			}
//	    });
		
		
		// Register Location Listner to update location
		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		//mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, this);
		myLocationManager= MyLocationManager.getMyLocationManager();
		myLocationManager.setLocationManager(this,mapController, mLocationManager);
		

		// geo fix 114.263949 22.336600
	}

	
	/**
	 * @param mapView MapView of Google Map
	 * To get lantitude and longtitude of four corners of the screen
	 */
	public void getScreenLocation(MapView mapView) {
		projection = mapView.getProjection();
		topLeft = projection.fromPixels(0, 0);
		bottomRight = projection.fromPixels(mapView.getWidth() - 1,
				mapView.getHeight() - 1);
		topLat = topLeft.getLatitudeE6() / 1E6;
		topLon = topLeft.getLongitudeE6() / 1E6;
		bottomLat = bottomRight.getLatitudeE6() / 1E6;
		bottomLon = bottomRight.getLongitudeE6() / 1E6;
	}


	/**
	 * initialize the MapView
	 */
	private void initMyLocation() {
		mLocationOverlay = new MyLocationOverlay(this, mapView);
		mapOverlays.add(mLocationOverlay);
		mLocationOverlay.enableCompass();
		mLocationOverlay.runOnFirstFix(new Runnable() {
			public void run() {
				mapController.animateTo(mLocationOverlay.getMyLocation());
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mLocationOverlay.enableMyLocation();
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		mLocationOverlay.disableMyLocation();
		
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	// ================================================================
	// Loading ItemOverlay From Database
	// ================================================================
	/**
	 * @author Sum
	 * To load all pets and mission in background thread by Asynctask
	 *
	 */
	class LoadItemFromDataBaseTask extends AsyncTask<Object, Object, Boolean>{
		ProgressDialog dialog;
		
		@Override
		protected void onPreExecute()
		{
			dialog=new ProgressDialog(mContext);
			dialog.setMessage("Loading, Please Wait.....");
			dialog.show();
		}
		@Override
		protected Boolean doInBackground(Object... params) {

			GlobalData.getInstance().getDbhelper().loadMapItem();
			
	        for (LocationData data : ItemListClass.getInstance().getItemList()){ // for all the rows in the cursor
	        // Get the spot's name, latitude and longitude
	        // Geopoint refers to the location. Need to specify latitude,
	        // longitude in microdegrees
		        if (data.getType()==2)
		        {
		        	 GeoPoint point = new GeoPoint((int)(data.getLat()*1e+6),(int)(data.getLng()*1e+6));
		 	        // Create an overlay item for the spot
		 	        AttractionSpot overlayitem = new AttractionSpot(point,data.getTitle(),data.getPic(),0);
		 	        Drawable drawable=getResources().getDrawable(getResources().getIdentifier(data.getPic(),"drawable","com.theydream.qeechain"));
		 	        drawable.setBounds(-36, -36	,36, 36);
		 	        overlayitem.setMarker(drawable);
		 	        // Add a proximity alert to the location that the user selected
//		 	        myLocationManager.addProximityAlert(data.getTitle(), (double)(point.getLatitudeE6()/1e6),(double)(point.getLongitudeE6()/1e6));
		 	        // Add the overlay item into the HelloItemizedOverlay for each spot
		 	        missionLayer.addOverlay(overlayitem);
		        }
		        
		        else
		        {
		        	 GeoPoint point = new GeoPoint((int)(data.getLat()*1e+6),(int)(data.getLng()*1e+6));
		 	        // Create an overlay item for the spot
		 	        AttractionSpot overlayitem = new AttractionSpot(point,data.getTitle(),data.getPic(),0);
		 	        Drawable drawable=getResources().getDrawable(getResources().getIdentifier(data.getPic(),"drawable","com.theydream.qeechain"));
		 	        drawable.setBounds(-36, -36, 36, 36);
		 	        overlayitem.setMarker(drawable);
		 	        // Add a proximity alert to the location that the user selected
//		 	        myLocationManager.addProximityAlert(data.getTitle(), (double)(point.getLatitudeE6()/1e6),(double)(point.getLongitudeE6()/1e6));
		 	        // Add the overlay item into the HelloItemizedOverlay for each spot
		 	        attLayer.addOverlay(overlayitem);
		 	      // Log.i("papapappapappapapa",this.getClass()..getPackage().getName());

		        }

	        }
	     // until you exhaust all the rows. returns false when we reach the end of the cursor
	        return true;
		}
		@Override
		protected void onPostExecute(Boolean bo)
		{
			dialog.dismiss();
			mapOverlays.add(attLayer);
			mapOverlays.add(missionLayer);
			mapController.setZoom(18);
			mapController.animateTo(new GeoPoint(22336904 ,114263333));
			mapView.invalidate();
			
		}
		
	}

}
